﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using YArchitech.Revit.Electric.Common;

namespace ElectricDim
{
	public static class DbFamilyObjectExtensions
	{
		public static Family LoadInSubTrans(this DbFamilyObject dbFamily, Document doc)
		{
			FileInfo fileInfo = new FileInfo(dbFamily.Family);
			Family family = null;
			try
			{
				string familyName = DbFamilyObjectExtensions.getFamilyName(fileInfo.FullName);
				family = ElementFiltering.FindFamily(doc, familyName);
				if (family == null)
				{
					Family family2 = null;
					SubTransaction subTransaction = new SubTransaction(doc);
					subTransaction.Start();
					doc.LoadFamily(fileInfo.FullName, out family2);
					subTransaction.Commit();
					family = family2;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			return family;
		}

		public static Family Load(this DbFamilyObject dbFamily, Document doc, ref FileInfo file)
		{
			file = new FileInfo(dbFamily.Family);
			Family family = null;
			try
			{
				string familyName = DbFamilyObjectExtensions.getFamilyName(file.FullName);
				family = ElementFiltering.FindFamily(doc, familyName);
				if (family == null)
				{
					Family family2 = null;
					Transaction transaction = new Transaction(doc, "LoadFamily");
					try
					{
						transaction.Start();
                        doc.LoadFamily(file.FullName, out family2);
						transaction.Commit();
						family = family2;
					}
					catch
					{
						transaction.RollBack();
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			return family;
		}

		public static Image GetImage(this DbFamilyObject dbFamily)
		{
			return Image.FromFile(dbFamily.Image2D);
		}

		private static string getFamilyName(string fullName)
		{
			int num = fullName.LastIndexOf("\\");
			int num2 = fullName.LastIndexOf(".");
			return fullName.Substring(num + 1, num2 - num - 1);
		}
	}
}
